package lang

import (
	"JVM/Jvmgo/GoToJVM/native"
	"JVM/Jvmgo/GoToJVM/runtimeData"
	"unsafe"
)

/*
注册getClass()方法
该方法返回对象的类对象引用
*/
func init() {
	native.Register("java/lang/Object", "getClass", "()Ljava/lang/Class;", getClass)
	native.Register("java/lang/Object", "hashCode", "()I", hashCode)
	native.Register("java/lang/Object", "clone", "()Ljava/lang/Object;", clone)
}

func getClass(frame *runtimeData.Frame) {
	this := frame.LocalVars().GetThis()
	class := this.Class().JClass()
	frame.OperandStack().PushRef(class)
}

// public native int hashCode
// 将 this 转换为一个 unsafe.Pointer 类型。
// unsafe.Pointer 是一种特殊的指针类型，它可以指向任何类型的值。
func hashCode(frame *runtimeData.Frame) {
	this := frame.LocalVars().GetThis()
	hash := int32(uintptr(unsafe.Pointer(this)))
	frame.OperandStack().PushInt(hash)
}

func clone(frame *runtimeData.Frame) {
	this := frame.LocalVars().GetThis()

	cloneable := this.Class().Loader().LoadClass("java/lang/Cloneable")
	if !this.Class().IsImplements(cloneable) {
		panic("java.lang.CloneNotSupportedException")
	}

	frame.OperandStack().PushRef(this.Clone())
}
